<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>哔哩哔哩创作中心 - 弹幕管理</title>
    <!-- 引入字体图标样式 -->
    <link rel="stylesheet" href="css/all.min.css">
    <!-- 网站图标 -->
    <link rel="icon" sizes="any" href="img/favicon.ico">
    <!-- 引入自定义样式 -->
    <link rel="stylesheet" href="css/danmakuManagement.css">
</head>

<body>
    <!-- 左侧导航栏 -->
    <div class="sidebar">
        <!-- 侧边栏 logo -->
        <div class="logo">
            <img src="img/favicon.ico" alt="Bilibili">
            <div class="logo-text">创作中心</div>
        </div>
        <!-- 投稿按钮 -->
        <button id="uploadBtn" class="upload-btn">
            <i class="fas fa-plus"></i> <span>投稿</span>
        </button>
        <!-- 导航菜单项 -->
        <a href="createCenter.html" class="nav-item">
            <i class="fas fa-home"></i> <span>首页</span>
        </a>
        <a href="contributionManagement.html" class="nav-item">
            <i class="fas fa-file-video"></i> <span>稿件管理</span>
        </a>
        <a href="commentManagement.html" class="nav-item">
            <i class="fas fa-comments"></i> <span>评论管理</span>
        </a>
        <a href="#" class="nav-item active">
            <i class="fas fa-closed-captioning"></i> <span>弹幕管理</span>
        </a>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部工具栏 -->
        <div class="top-bar">
            <!-- 搜索框和返回首页链接 -->
            <div class="search-box">
                <a href="index.html" style="text-decoration: none; color: #00A1D6;">
                    <span class="span1">
                        <svg width="18" height="18" viewBox="0 0 18 18" fill="none"
                            xmlns="http://www.w3.org/2000/svg" class="zhuzhan-icon">
                            <path fill-rule="evenodd" clip-rule="evenodd"
                                d="M3.73252 2.67094C3.33229 2.28484 3.33229 1.64373 3.73252 1.25764C4.11291 0.890684 4.71552 0.890684 5.09591 1.25764L7.21723 3.30403C7.27749 3.36218 7.32869 3.4261 7.37081 3.49407H10.5789C10.6211 3.4261 10.6723 3.36218 10.7325 3.30403L12.8538 1.25764C13.2342 0.890684 13.8368 0.890684 14.2172 1.25764C14.6175 1.64373 14.6175 2.28484 14.2172 2.67094L13.364 3.49407H14C16.2091 3.49407 18 5.28493 18 7.49407V12.9996C18 15.2087 16.2091 16.9996 14 16.9996H4C1.79086 16.9996 0 15.2087 0 12.9996V7.49406C0 5.28492 1.79086 3.49407 4 3.49407H4.58579L3.73252 2.67094ZM4 5.42343C2.89543 5.42343 2 6.31886 2 7.42343V13.0702C2 14.1748 2.89543 15.0702 4 15.0702H14C15.1046 15.0702 16 14.1748 16 13.0702V7.42343C16 6.31886 15.1046 5.42343 14 5.42343H4ZM5 9.31747C5 8.76519 5.44772 8.31747 6 8.31747C6.55228 8.31747 7 8.76519 7 9.31747V10.2115C7 10.7638 6.55228 11.2115 6 11.2115C5.44772 11.2115 5 10.7638 5 10.2115V9.31747ZM12 8.31747C11.4477 8.31747 11 8.76519 11 9.31747V10.2115C11 10.7638 11.4477 11.2115 12 11.2115C12.5523 11.2115 13 10.7638 13 10.2115V9.31747C13 8.76519 12.5523 8.31747 12 8.31747Z"
                                fill="currentColor"></path>
                        </svg>
                    </span>
                    <span class="span2" style="vertical-align: top;">首页</span>
                </a>
            </div>
            <!-- 用户操作区域，包含通知和用户信息 -->
            <div class="user-actions">
                <div class="notification">
                    <i class="fas fa-bell"></i>
                </div>
                <div class="user-profile">
                    <div class="user-avatar">UP</div>
                    <div class="username">创作UP主</div>
                </div>
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
            <!-- 页面标题 -->
            <h1 class="section-title">
                <i class="fas fa-closed-captioning"></i> 弹幕管理
            </h1>
            <!-- 弹幕统计卡片 -->
            <div class="stats-cards">
                <div class="stat-card">
                    <div class="stat-title">弹幕总数</div>
                    <div class="stat-value" id="danmakuCount"></div>
                </div>
                <div class="stat-card">
                    <div class="stat-title">屏蔽弹幕数</div>
                    <div class="stat-value" id="danmakuDownCount"></div>
                </div>
            </div>
            <!-- 弹幕管理区域 -->
            <div class="danmu-management">
                <div class="module-header">
                    <div class="module-title">弹幕管理</div>
                </div>
                <!-- 筛选区域 -->
                <div class="danmu-filters">
                    <div class="filter-group">
                        <label>视频筛选</label>
                        <div class="search-box">
                            <input type="text" id="videoFilter" placeholder="搜索视频">
                        </div>
                    </div>
                    <div class="filter-group">
                        <label>时间范围</label>
                        <select id="timeRange">
                            <option value="">全部时间</option>
                            <option value="7">最近7天</option>
                            <option value="30">最近30天</option>
                            <option value="90">最近3个月</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>关键词搜索</label>
                        <input type="text" id="keywordFilter" placeholder="输入弹幕关键词">
                    </div>
                    <button id="filterBtn" class="filter-btn">
                        <i class="fas fa-filter"></i> 筛选
                    </button>
                </div>
                <!-- 弹幕列表 -->
                <div class="danmu-list">
                    <div class="danmu-header">
                        <div class="header-content">弹幕内容</div>
                        <div class="header-video">所属视频</div>
                        <div class="header-time">发送时间</div>
                        <div class="header-status">状态</div>
                        <div class="header-actions">操作</div>
                    </div>
                </div>
                <!-- 分页控件 -->
                <div class="pagination">
                    <div class="page-btn prev-btn" data-page="1">
                        <i class="fas fa-chevron-left"></i>
                    </div>
                    <div class="page-numbers"></div>
                    <div class="page-btn next-btn" data-page="1">
                        <i class="fas fa-chevron-right"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 投稿模态框 -->
    <div id="uploadModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-title">投稿新视频</div>
            <button class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label for="videoTitle">视频标题</label>
                <input type="text" id="videoTitle" placeholder="输入视频标题">
            </div>
            <div class="form-group">
                <label for="videoDesc">视频简介</label>
                <textarea id="videoDesc" placeholder="输入视频简介"></textarea>
            </div>
            <div class="form-group">
                <label for="videoCategory">视频分区</label>
                <select id="videoCategory">
                    <option value="">选择视频分区</option>
                    <option value="游戏">游戏</option>
                    <option value="音乐">音乐</option>
                    <option value="知识">知识</option>
                    <option value="科技">科技</option>
                    <option value="生活">生活</option>
                    <option value="娱乐">娱乐</option>
                </select>
            </div>
            <div class="form-group">
                <label>上传视频文件</label>
                <div class="file-upload" id="videoUpload">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p>点击或拖拽文件到此处上传</p>
                    <p class="small">支持MP4、MOV、AVI等格式，最大2GB</p>
                    <input type="file" id="videoFileInput" accept="video/*" style="display:none;">
                </div>
            </div>
            <div class="form-group">
                <label>上传封面图片</label>
                <div class="file-upload" id="coverUpload">
                    <i class="fas fa-image"></i>
                    <p>点击或拖拽文件到此处上传</p>
                    <p class="small">支持JPG、PNG格式，建议尺寸1146x717</p>
                    <input type="file" id="coverFileInput" accept="image/*" style="display:none;">
                </div>
            </div>
            <input type="hidden" id="durationInSeconds" name="durationInSeconds">
        </div>
        <div class="modal-footer">
            <button class="btn-submit" id="btn-submit">发布投稿</button>
        </div>
    </div>
</div>

    <!-- 引入自定义 JavaScript 文件 -->
    <!-- <script src="js/danmakuManagement.js"></script> -->
    <!-- 引入 jQuery 库 -->
    <script src="js/jquery.js"></script>
    <script>
    let userNameB = $(".username")
    let avatar = $(".user-avatar")
    $.ajax({
    	url:"userSession",
    	type:"post",
    	success:function(data){
    		if(data.code == 200){
    			userNameB.text(data.data.nickname)
    			avatar.css({
    				"background-image":"url("+data.data.avatarUrl+")",
    				"background-size":"cover"
    			})
    			avatar.text("")
    		}
    	}
    })
    let videoFile = null;
    let coverFile = null;
    let isFormSubmitInitialized = false;
    let isNavigationInitialized = false;
    let isModalInitialized = false;

    // 初始化文件上传区域
    function initFileUploads() {
        // 创建并缓存文件输入元素
        const videoFileInput = document.getElementById('videoFileInput') || createFileInput('videoUpload');

        
        const coverFileInput = document.getElementById('coverFileInput') || createFileInput('coverUpload');
        
        // 获取上传区域
        const videoUpload = document.getElementById('videoUpload');
        const coverUpload = document.getElementById('coverUpload');
        
        // 防止重复绑定事件
        if (!videoUpload._initialized) {
            // 设置拖放功能
            setupDragDrop(videoUpload, videoFileInput, 'video');
            setupDragDrop(coverUpload, coverFileInput, 'image');
            
            // 设置点击功能
            videoUpload.addEventListener('click', () => videoFileInput.click());
            coverUpload.addEventListener('click', () => coverFileInput.click());
            
            // 监听文件选择变化
            videoFileInput.addEventListener('change', () => handleFileSelection(videoFileInput, videoUpload, 'video'));
            coverFileInput.addEventListener('change', () => handleFileSelection(coverFileInput, coverUpload, 'image'));
            
            // 标记为已初始化
            videoUpload._initialized = true;
            coverUpload._initialized = true;
        }
    }

    // 创建隐藏的文件输入元素
    function createFileInput(id) {
        const input = document.createElement('input');
        input.type = 'file';
        input.id = `${id}Input`;
        input.style.display = 'none';
        input.accept = id === 'videoUpload' ? 'video/*' : 'image/*';
        document.body.appendChild(input);
        return input;
    }

    // 设置拖放功能
    function setupDragDrop(uploadArea, fileInput, type) {
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#00A1D6';
            this.style.backgroundColor = 'rgba(0, 161, 214, 0.1)';
        });

        uploadArea.addEventListener('dragleave', function() {
            this.style.borderColor = '';
            this.style.backgroundColor = '';
        });

        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '';
            this.style.backgroundColor = '';

            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                handleFileSelection(fileInput, uploadArea, type);
            }
        });
    }

    // 处理文件选择
    function handleFileSelection(fileInput, uploadArea, type) {
        if (fileInput.files.length) {
            const file = fileInput.files[0];
            
            // 更新全局变量
            if (type === 'video') {
                videoFile = file;
                uploadArea.innerHTML = `
                    <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                    <p>${file.name}</p>
                    <p class="small">计算时长中...</p>
                `;
                getVideoDuration(file).then(duration => {
                	const durationInSeconds = Math.floor(duration);
                    console.log('视频时长（秒）:', durationInSeconds);
                    // 确保设置到隐藏字段
                    document.getElementById('durationInSeconds').value = durationInSeconds;
                    // 更新UI显示时长
                    uploadArea.innerHTML = `
                        <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                        <p>${file.name}</p>
                        <p class="small">时长: ${formatDuration(duration)}</p>
                        <p class="small" style="color:#4CAF50;">视频已选择</p>
                    `;
                }).catch(error => {
                    console.error('获取视频时长失败:', error);
                    document.getElementById('durationInSeconds').value = 0;
                    uploadArea.innerHTML = `
                        <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                        <p>${file.name}</p>
                        <p class="small" style="color:#FF5722;">时长计算失败</p>
                        <p class="small" style="color:#4CAF50;">视频已选择</p>
                    `;   
                });
            } else {
            	coverFile = file;
            	uploadArea.innerHTML = `
                    <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                    <p>${file.name}</p>
                    <p class="small" style="color:#4CAF50;">封面已选择</p>
                `;
            }
            
            // 更新UI显示
            uploadArea.innerHTML = `
                <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                <p>${file.name}</p>
                <p class="small" style="color:#4CAF50;">${type === 'video' ? '视频' : '封面'}已选择</p>
            `;
            
            // 重新绑定点击事件（因为innerHTML会移除原有的事件监听器）
            const fileInputEl = document.getElementById(`${uploadArea.id}Input`);
            uploadArea.addEventListener('click', () => fileInputEl.click());
        }
    }
    function getVideoDuration(file) {
    	return new Promise((resolve, reject) => {
            const video = document.createElement('video');
            const url = URL.createObjectURL(file);
            
            video.onloadedmetadata = () => {
                URL.revokeObjectURL(url); // 释放内存
                if (video.duration && video.duration > 0) {
                    resolve(video.duration);
                } else {
                    reject(new Error('无法获取有效视频时长'));
                }
            };
            
            video.onerror = () => {
                URL.revokeObjectURL(url);
                reject(new Error('视频加载失败'));
            };
            
            video.src = url;
            
            // 设置超时处理
            setTimeout(() => {
                if (video.readyState >= 1 && video.duration > 0) {
                    URL.revokeObjectURL(url);
                    resolve(video.duration);
                } else {
                    URL.revokeObjectURL(url);
                    reject(new Error('获取视频时长超时'));
                }
            }, 5000); // 5秒超时
        });
    }

    // 新增：格式化时长的函数
    function formatDuration(seconds) {
        const h = Math.floor(seconds / 3600);
        const m = Math.floor((seconds % 3600) / 60);
        const s = Math.floor(seconds % 60);
        
        if (h > 0) {
            return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
        } else {
            return `${m}:${s.toString().padStart(2, '0')}`;
        }
    }

    // 初始化表单提交（防止重复绑定）
    function initFormSubmit() {
    if (isFormSubmitInitialized) return;
        
        $("#btn-submit").off('click.submitHandler').on('click.submitHandler', function(e) {
            e.preventDefault();
            
            // 验证表单
            if (!videoFile) {
                alert('请选择视频文件');
                return;
            }
            
            // 确保获取时长值
            const durationInSeconds = document.getElementById('durationInSeconds').value || 0;
            
            const formData = new FormData();
            
            // 添加文本字段
            formData.append('videoTitle', $('#videoTitle').val());
            formData.append('videoDesc', $('#videoDesc').val());
            formData.append('videoCategory', $('#videoCategory').val());
            formData.append('durationInSeconds', durationInSeconds); // 明确添加时长字段
            
            // 添加文件
            formData.append('videoFile', videoFile);
            if (coverFile) formData.append('coverFile', coverFile);
            // 发送Ajax请求
            $.ajax({
                type: "POST",
                url: "createCenter.do",
                data: formData,
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $("#btn-submit").html('<i class="fas fa-spinner fa-spin"></i> 上传中...').prop('disabled', true);
                },
                success: function(data) {
                    console.log("上传成功:", data);
                    alert('投稿成功！');
                    uploadModal.style.display = 'none';
                    document.body.style.overflow = 'auto';
                    resetUploadForm();
                },
                error: function(xhr, status, error) {
                    console.error("上传失败:", error);
                    alert('投稿失败：' + (xhr.responseJSON ? xhr.responseJSON.message : '网络错误'));
                },
                complete: function() {
                    $("#btn-submit").html('发布投稿').prop('disabled', false);
                }
            });
        });
        
        isFormSubmitInitialized = true;
    }

    // 重置上传表单
    function resetUploadForm() {
        videoFile = null;
        coverFile = null;
        
        // 重置UI显示
        $('#videoUpload').html(`
            <i class="fas fa-cloud-upload-alt"></i>
            <p>点击或拖拽视频到此处</p>
            <p class="small">支持MP4、MOV、AVI等格式，最大2GB</p>
        `);
        
        $('#coverUpload').html(`
            <i class="fas fa-image"></i>
            <p>点击或拖拽封面到此处</p>
            <p class="small">支持JPG、PNG格式，建议尺寸1146x717</p>
        `);
        
        // 清空表单字段
        $('#videoTitle').val('');
        $('#videoDesc').val('');
        $('#videoCategory').val('');
    }

    // 初始化导航栏交互（防止重复绑定）
    function initNavigation() {
        if (isNavigationInitialized) return;
        
        const navItems = document.querySelectorAll('.nav-item');
        navItems.forEach(item => {
            item.removeEventListener('click', handleNavClick);
            item.addEventListener('click', handleNavClick);
        });
        
        isNavigationInitialized = true;
    }

    // 导航栏点击处理函数
    function handleNavClick(e) {
        const navItems = document.querySelectorAll('.nav-item');
        navItems.forEach(nav => nav.classList.remove('active'));
        this.classList.add('active');

        // 更新页面标题
        const title = this.querySelector('span').textContent;
        document.querySelector('.section-title').innerHTML =
            `<i class="${this.querySelector('i').className}"></i> ${title}`;
    }

    // 初始化模态框交互（防止重复绑定）
    function initModal() {
        if (isModalInitialized) return;
        
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadModal = document.getElementById('uploadModal');
        const closeBtn = document.querySelector('.close-btn');

        $(uploadBtn).off('click.modal').on('click.modal', function() {
            uploadModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        });

        $(closeBtn).off('click.modal').on('click.modal', function() {
            uploadModal.style.display = 'none';
            document.body.style.overflow = 'auto';
        });

        $(window).off('click.modal').on('click.modal', function(event) {
            if (event.target === uploadModal) {
                uploadModal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });
        
        isModalInitialized = true;
    }
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded事件触发');
        initFileUploads();
        initFormSubmit();
        initNavigation();
        initModal();
        allVideo(); // 加载视频
        showLatestComments(); // 加载最新评论
        
        // 额外添加定时刷新评论（测试用）
        setInterval(showLatestComments, 5000); // 每5秒刷新一次
    });
    showViewCount();
    function showViewCount(){
    	$.ajax({
            type: "GET",
            url: "allViewCount.do",
            data: {
            	
            },
            success: function(data) {
            	$("#viewCount").append(data.data);
            }
            
        });
    	
    }
    showFollowerCount();
    function showFollowerCount(){
    	$.ajax({
            type: "GET",
            url: "allFollowerCount.do",
            data: {
            	
            },
            success: function(data) {
            	$("#followerCount").append(data.data);
            }
            
        });
    	
    }
    function queryCommentCount(videoId) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "GET",
                url: "oneComment.do",
                data: { e: videoId },
                success: function(data) {
                    resolve(data.data);
                },
                error: function(error) {
                    console.error("获取评论数失败:", error);
                    resolve(0); // 失败时返回0
                }
            });
        });
    }
    async function allVideo() {
        try {
            const videoResponse = await $.ajax({
                type: "GET",
                url: "allVideo.do"
            });

            const videoData = videoResponse.data;
            const videoContainer = $("#video-manage");
            videoContainer.empty();

            // 限制只显示5个视频
            const videosToShow = videoData.slice(0, 5);
            
            const videoItems = await Promise.all(videosToShow.map(async video => {
                const commentCount = await queryCommentCount(video.videoId);
                const latestComments = await getLatestComments(video.videoId);
                return { video, commentCount, latestComments };
            }));

            // 渲染视频列表
            videoItems.forEach(item => {
                const { video, commentCount } = item;
                const formatTime = (seconds) => {
                    const mins = Math.floor(seconds / 60);
                    const secs = Math.floor(seconds % 60);
                    return `${mins}:${secs.toString().padStart(2, '0')}`;
                };
                let coverUrl = video.coverUrl || "";
                coverUrl = coverUrl === "/bilibili/material/img/cover/null" 
                          ? "/bilibili/material/img/cover/default.jpg" 
                          : coverUrl;
                
                videoContainer.append(`
                    <div class="video-item">
                        <div class="video-thumb" style="background-image: url('${coverUrl}'); background-size: cover; background-position: center;">
                            <div class="video-duration">${formatTime(video.duration)}</div>
                        </div>
                        <div class="video-info">
                            <div class="video-title">${video.title}</div>
                            <div class="video-stats">
                                <div class="stat-item"><i class="fas fa-play"></i> ${video.viewCount}</div>
                                <div class="stat-item"><i class="fas fa-comment"></i> ${commentCount}</div>
                                <div class="stat-item"><i class="fas fa-heart"></i> ${video.likeCount}</div>
                            </div>
                        </div>
                    </div>
                `);
            });
        } catch (error) {
            console.error("获取视频数据失败:", error);
        }
    }

    async function showLatestComments() {
        try {
            const videoResponse = await $.ajax({
                type: "GET",
                url: "allVideo.do",
                error: () => {
                    console.error("获取视频列表失败");
                    return { data: [] };
                }
            });
            
            const videoIds = videoResponse.data.map(video => video.videoId);
            if (videoIds.length === 0) {
                console.log("没有视频数据，跳过评论加载");
                return;
            }
            
            // 并行获取所有视频的评论（优化版）
            const commentPromises = videoIds.map(videoId => 
                $.ajax({
                    type: "GET",
                    url: "threeComment.do",
                    data: { e: videoId },
                    timeout: 5000,
                    error: (xhr, status, err) => ({ data: [] })
                })
            );
            
            const allComments = await Promise.all(commentPromises);
            const mergedComments = allComments
                .flatMap(res => res.data || [])
                .filter(comment => comment.createTime)
                .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                .slice(0, 3);
            
            const commentsContainer = $(".right-column .video-list").first();
            if (mergedComments.length === 0) {
                commentsContainer.html(`
                    <div class="no-comments">暂无评论</div>
                `);
                return;
            }
            
            commentsContainer.empty();
            mergedComments.forEach(comment => {
                commentsContainer.append(`
                    <div class="video-item" style="border-left: 3px solid #00A1D6; padding-left: 10px;">
                        <div class="video-info">
                            <div class="video-title" style="font-weight: bold;">${comment.username}：${comment.content}</div>
                            <div class="video-stats" style="color: #999;">${formatDate(comment.createTime)} · 
                                <i class="fas fa-thumbs-up" style="margin-right: 5px;"></i>${comment.likeCount || 0}
                            </div>
                        </div>
                    </div>
                `);
            });
            
        } catch (error) {
            console.error("评论加载异常:", error);
        }
    }
    async function getLatestComments(videoId) {
        try {
            const response = await $.ajax({
                type: "GET",
                url: "threeComment.do",
                data: { e: videoId }
            });
            return response.data || [];
        } catch (error) {
            console.error("获取评论失败:", error);
            return [];
        }
    }
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    // 页面加载完成后初始化所有功能

        // 全局常量定义，定义弹幕状态
        const DANMAKU_STATUS = {
            APPROVED: 1,  // 已通过（数据库中status=1）
            BLOCKED: 0    // 已屏蔽（数据库中status=0）
        };

        // 全局变量
        let currentPage = 1;          // 当前页码
        let totalPages = 1;           // 总页数
        let pageSize = 10;            // 每页显示数量
        let upId = 1;                 // 假设当前UP主ID为1，实际应从会话获取

        // 筛选参数
        let filterParams = {
            keyword: "",
            timeRange: "",
            videoTitle: ""
        };

        // 页面加载完成后执行
        $(document).ready(function () {
            initPage();
            bindEvents();
            loadDanmakuByPage(1);
        });

        /**
         * 初始化页面基础数据
         */
        function initPage() {
            loadDanmakuCount();
            loadBlockedDanmakuCount();
        }

        /**
         * 绑定所有事件
         */
        function bindEvents() {
            // 分页按钮点击事件
            $(document).on('click', '.page-btn.prev-btn, .page-btn.next-btn', handlePaginationClick);
            $(document).on('click', '.page-number', handlePaginationClick);

            // 弹幕状态切换事件
            $(document).on('click', '.action-icon.block', function () {
                toggleDanmakuStatus(this, DANMAKU_STATUS.BLOCKED);
            });
            $(document).on('click', '.action-icon.approve', function () {
                toggleDanmakuStatus(this, DANMAKU_STATUS.APPROVED);
            });

            // 筛选按钮点击事件
            $("#filterBtn").on("click", applyFilters);

            // 输入框回车事件
            $("#videoFilter, #keywordFilter").on("keypress", function (e) {
                if (e.which === 13) {
                    applyFilters();
                }
            });

            // 时间范围选择事件
            $("#timeRange").on("change", applyFilters);
        }

        /**
         * 应用筛选条件
         */
        function applyFilters() {
            filterParams.keyword = $("#keywordFilter").val().trim();
            filterParams.timeRange = $("#timeRange").val();
            filterParams.videoTitle = $("#videoFilter").val().trim();

            showFilterLoading(); // 显示加载状态
            loadDanmakuByPage(1); // 重新加载第一页数据
        }

        /**
         * 处理分页点击事件
         */
        function handlePaginationClick(e) {
            if ($(this).hasClass('disabled')) return;

            let page = $(this).data('page');
            if ($(this).hasClass('prev-btn')) {
                page = currentPage - 1;
            } else if ($(this).hasClass('next-btn')) {
                page = currentPage + 1;
            }

            loadDanmakuByPage(page);
        }

        /**
         * 按页码加载弹幕数据
         */
        function loadDanmakuByPage(pageNum) {
            currentPage = pageNum;
            showLoading();

            $.ajax({
                type: "GET",
                url: "danmaku.do",
                data: {
                    upId: upId,
                    pageNum: pageNum,
                    pageSize: pageSize,
                    keyword: filterParams.keyword,
                    timeRange: filterParams.timeRange,
                    videoTitle: filterParams.videoTitle
                },
                success: function (response) {
                    hideLoading();
                    hideFilterLoading(); // 隐藏筛选按钮加载状态
                    processDanmakuResponse(response);
                },
                error: function () {
                    hideLoading();
                    hideFilterLoading(); // 隐藏筛选按钮加载状态
                    alert("网络请求失败，请检查连接");
                }
            });
        }

        /**
         * 处理弹幕响应数据
         */
        function processDanmakuResponse(response) {
            if (response.code !== 200) {
                alert("获取弹幕数据失败：" + response.message);
                return;
            }

            const page = response.data;
            totalPages = page.totalPages;
            const danmakuList = page.data;

            $("#danmakuCount").text(page.totalRows);
            loadBlockedDanmakuCount();

            // 清空现有弹幕列表
            $('.danmu-list > .danmu-item:not(.danmu-header)').remove();

            // 渲染弹幕列表
            danmakuList.forEach(renderDanmakuItem);

            // 更新分页控件
            updatePagination();
        }

        /**
         * 渲染单个弹幕项
         */
        function renderDanmakuItem(danmaku) {
            // 确定弹幕状态
            const status = danmaku.status === DANMAKU_STATUS.APPROVED ? {
                class: 'status-normal',
                text: '已通过',
                actionClass: 'block',
                actionIcon: 'fa-ban',
                actionTitle: '屏蔽'
            } : {
                class: 'status-blocked',
                text: '已屏蔽',
                actionClass: 'approve',
                actionIcon: 'fa-check',
                actionTitle: '通过'
            };

            // 格式化日期（仅显示年月日）
            const createTime = formatDate(danmaku.createTime);

            // 构建弹幕项HTML
            const danmuItem = `
                <div class="danmu-item" data-danmaku-id="${danmaku.danmakuId}">
                    <div class="danmu-content">${danmaku.content}</div>
                    <div class="danmu-video">${danmaku.videoTitle || '未指定视频'}</div>
                    <div class="danmu-time">${createTime}</div>
                    <div class="danmu-status ${status.class}">${status.text}</div>
                    <div class="danmu-actions">
                        <div class="action-icon ${status.actionClass}" title="${status.actionTitle}">
                            <i class="fas ${status.actionIcon}"></i>
                        </div>
                    </div>
                </div>
            `;

            // 添加到弹幕列表
            $('.danmu-list').append(danmuItem);
        }

        /**
         * 切换弹幕状态
         */
        function toggleDanmakuStatus(btn, targetStatus) {
            const danmakuId = $(btn).closest('.danmu-item').data('danmaku-id');
            if (!danmakuId) return;

            showActionLoading(btn);

            $.ajax({
                type: "POST",
                url: "updateDanmakuStatus.do",
                data: {
                    danmakuId: danmakuId,
                    status: targetStatus
                },
                success: function (result) {
                    hideActionLoading(btn);

                    if (result.code === 200) {
                        const danmuItem = $(btn).closest('.danmu-item');
                        const newStatus = targetStatus === DANMAKU_STATUS.APPROVED ? {
                            class: 'status-normal',
                            text: '已通过',
                            actionClass: 'block',
                            actionIcon: 'fa-ban',
                            actionTitle: '屏蔽'
                        } : {
                            class: 'status-blocked',
                            text: '已屏蔽',
                            actionClass: 'approve',
                            actionIcon: 'fa-check',
                            actionTitle: '通过'
                        };

                        // 更新状态显示
                        danmuItem.find('.danmu-status')
                            .removeClass('status-normal status-blocked')
                            .addClass(newStatus.class)
                            .text(newStatus.text);

                        const actionIcon = danmuItem.find('.action-icon:first');
                        actionIcon
                            .removeClass('block approve')
                            .addClass(newStatus.actionClass);
                        actionIcon.find('i')
                            .removeClass('fa-ban fa-check')
                            .addClass(newStatus.actionIcon);
                        actionIcon.attr('title', newStatus.actionTitle);

                        // 刷新计数
                        loadDanmakuCount();
                        loadBlockedDanmakuCount();

                        // 500ms后重新加载当前页数据
                        setTimeout(() => {
                            loadDanmakuByPage(currentPage);
                        }, 500);
                    } else {
                        alert("操作失败：" + result.message);
                    }
                },
                error: function () {
                    hideActionLoading(btn);
                    alert("网络错误，操作未完成");
                }
            });
        }

        /**
         * 加载弹幕总数
         */
        function loadDanmakuCount() {
            $.ajax({
                type: "GET",
                url: "countDanmaku.do",
                data: {
                    upId: upId
                },
                success: function (result) {
                    if (result.code === 200) {
                        $("#danmakuCount").text(result.data || 0);
                    }
                }
            });
        }

        /**
         * 加载屏蔽弹幕数
         */
        function loadBlockedDanmakuCount() {
            $.ajax({
                type: "GET",
                url: "countBlockedDanmaku.do",
                data: {
                    upId: upId
                },
                success: function (result) {
                    if (result.code === 200) {
                        $("#danmakuDownCount").text(result.data || 0);
                    }
                }
            });
        }

        /**
         * 更新分页控件
         */
        function updatePagination() {
            $('.page-numbers').empty();
            $('.prev-btn').data('page', currentPage - 1);
            $('.next-btn').data('page', currentPage + 1);

            // 禁用按钮状态
            if (currentPage <= 1) {
                $('.prev-btn').addClass('disabled');
            } else {
                $('.prev-btn').removeClass('disabled');
            }

            if (currentPage >= totalPages) {
                $('.next-btn').addClass('disabled');
            } else {
                $('.next-btn').removeClass('disabled');
            }

            // 生成分页号码（智能显示）
            let startNum, endNum;
            if (totalPages <= 5) {
                startNum = 1;
                endNum = totalPages;
            } else if (currentPage <= 3) {
                startNum = 1;
                endNum = 5;
            } else if (currentPage >= totalPages - 2) {
                startNum = totalPages - 4;
                endNum = totalPages;
            } else {
                startNum = currentPage - 2;
                endNum = currentPage + 2;
            }

            // 插入页码
            for (let i = startNum; i <= endNum; i++) {
                const pageNumber = $('<span>')
                   .addClass('page-number')
                   .data('page', i)
                   .text(i);

                if (i === currentPage) {
                    pageNumber.addClass('active');
                }

                $('.page-numbers').append(pageNumber);
            }
        }

        /**
         * 显示加载状态
         */
        function showLoading() {
            // 可以在这里添加加载动画
        }

        /**
         * 隐藏加载状态
         */
        function hideLoading() {
            $('.loading').remove();
        }

        /**
         * 显示筛选按钮加载状态
         */
        function showFilterLoading() {
            const filterBtn = $("#filterBtn");
            const originalText = filterBtn.html();

            filterBtn.html('<i class="fas fa-spinner fa-spin"></i> 筛选中...');
            filterBtn.attr("disabled", "disabled");

            // 保存原始文本以便恢复
            filterBtn.data("originalText", originalText);
        }

        /**
         * 隐藏筛选按钮加载状态
         */
        function hideFilterLoading() {
            const filterBtn = $("#filterBtn");
            if (filterBtn.data("originalText")) {
                filterBtn.html(filterBtn.data("originalText"));
                filterBtn.removeAttr("disabled");
            }
        }

        /**
         * 显示操作加载状态
         */
        function showActionLoading(btn) {
            $(btn).closest('.danmu-actions').append('<span class="action-loading">...</span>');
        }

        /**
         * 隐藏操作加载状态
         */
        function hideActionLoading(btn) {
            $('.action-loading').remove();
        }

        /**
         * 日期格式化（仅保留年月日，移除时分秒）
         */
        function formatDate(date) {
            // 检查 date 是否为 Date 对象，如果不是则尝试转换
            if (!(date instanceof Date)) {
                date = new Date(date);
            }
            // 检查转换后的 date 是否为有效的日期
            if (isNaN(date.getTime())) {
                return 'Invalid Date';
            }
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`; // 只返回年月日部分
        }

        /**
         * 数字补零
         */
        function padZero(num) {
            return num < 10 ? "0" + num : num.toString();
        }
    </script>
</body>

</html>